//
//  ZYXSearchVC.m
//  RuiBeiKang
//
//  Created by iOS开发1 on 2019/1/7.
//  Copyright © 2019年 JW. All rights reserved.
//

#import "ZYXSearchVC.h"

#import "ZYXSearchTopView.h"

#import "ZYXSearchCell.h"
#import "ZYXSearchReusableView.h"

#import "ZYXSearchResultVC.h"
@interface ZYXSearchVC ()<UITextFieldDelegate>
/// 假导航
@property (nonatomic,strong) ZYXSearchTopView *topSearchView;
@property (nonatomic,strong) NSMutableArray *hotArr;
@property (nonatomic,strong) NSMutableArray *historyArr;
@end

@implementation ZYXSearchVC

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:YES];

}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//    self.hotArr = [NSMutableArray arrayWithObjects:@"财务会计",@"建筑学",@"医疗健康",@"企业管理",@"企业管理",@"数据分析",@"工程建造",@"IT编程", nil];
    
}
-(void)setupViews{
    
    [self setupTopNavView];
    
    UICollectionViewFlowLayout *fl = [[UICollectionViewFlowLayout alloc]init];
    fl.scrollDirection = UICollectionViewScrollDirectionVertical;
    
    self.collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(0, NavigationBar_Height, SCREEN_WIDTH, SCREEN_HEIGHT - NavigationBar_Height) collectionViewLayout:fl];
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.scrollEnabled = YES;
    self.collectionView.showsVerticalScrollIndicator = NO;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZYXSearchCell" bundle:nil] forCellWithReuseIdentifier:@"ZYXSearchCell"];
    [self.collectionView registerNib:[UINib nibWithNibName:@"ZYXSearchReusableView" bundle:nil] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZYXSearchReusableView"];
    [self.view addSubview:self.collectionView];
}
-(void)loadData{
    [NetWork GETWithUrlString:kInterfaceAllUrl(PATH_IndexSearchHot) parmas:@{} successBloock:^(NSDictionary *responseObject) {
        NSLog(@"%@",responseObject);
        if ([responseObject[@"code"] isEqualToNumber:@200]) {
            self.hotArr = [NSMutableArray arrayWithArray:responseObject[@"data"]];
            [self.collectionView reloadData];
            
        }else{
            [JKToast showWithText:responseObject[@"message"]];
        }
        
    } failureBlock:^(NSError *error) {
        
    }];
}
/// 假导航栏
- (void)setupTopNavView {
    ZYXSearchTopView *searchView = [[NSBundle mainBundle] loadNibNamed:@"ZYXSearchTopView" owner:nil options:nil].lastObject;
    _topSearchView = searchView;

    [self.view addSubview:searchView];
//    searchView.frame = CGRectMake(0, 0, SCREEN_WIDTH, NavigationBar_Height);
    [searchView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(20);
        make.left.offset(0);
        make.right.offset(0);
        make.height.offset(NavigationBar_Height-StatusBar_Height);
    }];
    searchView.searchImg = IMG(@"sousuo");
    searchView.searchField.placeholder = @"请输入您要搜索的课程";
    searchView.searchField.delegate = self;
    [searchView.cancelBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
      [searchView.backBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
}
// MARK: -- textfield代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [self.view endEditing:YES];
    if (STR_Is_NullOrEmpty(textField.text)) { return YES; }
    
    NSArray *arr = [USERDEFAULT objectForKey:History1];
    if (arr.count <=7) {
        if (arr != nil) {
            NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:arr];
            if ([mutableArr containsObject:textField.text]) {
                [mutableArr removeObject:textField.text];
                [mutableArr insertObject:textField.text atIndex:0];
                arr = mutableArr;
            } else {
                [mutableArr insertObject:textField.text atIndex:0];
                arr = mutableArr;
            }
        } else {
            arr = @[textField.text];
        }
        [USERDEFAULT setObject:arr forKey:History1];
        [self.collectionView reloadData];
    }else if (arr.count == 8) {
        NSMutableArray *mutableArr = [NSMutableArray arrayWithArray:arr];
        if (arr != nil) {
      
            if ([mutableArr containsObject:textField.text]) {
                [mutableArr removeObject:textField.text];
                [mutableArr insertObject:textField.text atIndex:0];
                arr = mutableArr;
            } else {
                [mutableArr insertObject:textField.text atIndex:0];
                 [mutableArr removeObjectAtIndex:8];
                arr = mutableArr;
            }
        } else {
           
        }
        
        [USERDEFAULT setObject:arr forKey:History1];
        [self.collectionView reloadData];
        
    }
  
  
    
    
    
    ZYXSearchResultVC *vc = [[ZYXSearchResultVC alloc]init];
    vc.searchStr = textField.text;
    [self.navigationController pushViewController:vc animated:YES];
    
    textField.text = @"";
    return YES;
}
#pragma mark collectionDelegate
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    if ([self isHistory]) {
        return 2;
    } else {
        return 1;
    }
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    
    if (section == 0) {
            return self.hotArr.count;
    } else {
        NSArray *arr =  [USERDEFAULT objectForKey:History1];
        return arr.count;
    }
    
}
-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    ZYXSearchCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ZYXSearchCell" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        cell.titleLabel.text = self.hotArr[indexPath.row];
    }else{
        NSArray *arr =  [USERDEFAULT objectForKey:History1];
        cell.titleLabel.text = arr[indexPath.row];
    
    }
    return cell;
    
    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    
    CGFloat TwoCellW = (SCREEN_WIDTH -HEIGHT(50))/4.0f;
    CGFloat TwoCellH = HEIGHT(32);
    return CGSizeMake(TwoCellW, TwoCellH);
    
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{

        return UIEdgeInsetsMake(0, HEIGHT(10), HEIGHT(10), HEIGHT(10));

}
-(UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{

    ZYXSearchReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"ZYXSearchReusableView" forIndexPath:indexPath];
    if (indexPath.section == 0) {
        view.titleLabel.text = @"热门搜索";
        view.delectView.hidden = YES;
        
    }else{
        view.titleLabel.text = @"历史搜索";
        view.delectView.hidden = NO;
        [view.delectBtn addTarget:self action:@selector(clickDelectAll) forControlEvents:UIControlEventTouchUpInside];
    }
        return view;
      

    
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
  
        return CGSizeMake(SCREEN_WIDTH, HEIGHT(50));
}
-(void)clickDelectAll{
    [USERDEFAULT setObject:@[] forKey:History1];
    [self.collectionView reloadData];
}
/// 历史记录是否为空
- (BOOL)isHistory {
    NSArray *arr = [USERDEFAULT objectForKey:History1];
    if (arr != nil && arr.count > 0) {
        return YES;
    }
    return NO;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    NSLog(@"点击事件");
    if (indexPath.section == 0) {
        self.topSearchView.searchField.text = self.hotArr[indexPath.row];
        NSLog(@"点击热搜:%@",self.hotArr[indexPath.row]);
        [self textFieldShouldReturn:self.topSearchView.searchField];

    }else if (indexPath.section == 1){
        NSArray *arr =  [USERDEFAULT objectForKey:History1];
        self.topSearchView.searchField.text = arr[indexPath.row];
        
        NSLog(@"点击历史:%@",arr[indexPath.row]);
             [self textFieldShouldReturn:self.topSearchView.searchField];

    }
        
}
// MARK: -- 懒加载
- (NSMutableArray *)hotArr {
    if(!_hotArr) {
        _hotArr = [NSMutableArray array];
        
    }
    return _hotArr;
}
@end
